#include "date.h"
#include "DateParser.hpp"

#include <string.h>
#include <stdio.h>

///////////////////////////////////////////////////////////////////////////////

// #define FILE_TRACE

#include "file_trace.h"

///////////////////////////////////////////////////////////////////////////////

//------------------------------------------------------------------------------
// static variables
//------------------------------------------------------------------------------

static DateParser s_parser;
static SYSTEMTIME* s_systime = NULL;
static char s_date_time_buffer[1024];

//------------------------------------------------------------------------------
// static functions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// public functions
//------------------------------------------------------------------------------

char *
DATE_GetSystemDateTime()
{
    char * ctime_string;    
    time_t rawtime;
    char * new_string;

    time(&rawtime);
    ctime_string = ctime(&rawtime);

    // for some reason the returned string ends with '\n'
    // but that messes up SMTP if used as is within the header
    // so overwrite the '\n'
    ctime_string[strlen(ctime_string) - 1] = '\0';

    new_string = (char *)malloc(strlen(ctime_string) + 1);
    strcpy(new_string, ctime_string); 

    return new_string;
}

int 
DATE_GetDayOfMonth(const time_t input_time)
{
    struct tm * timeinfo;

    timeinfo = localtime(&input_time);

    return timeinfo->tm_mday;
}

char *
DATE_GetPreviousMonthAndYearString()
{
    time_t rawtime;
    struct tm * timeinfo;

    time(&rawtime);
    timeinfo = localtime(&rawtime);
    strftime(s_date_time_buffer, sizeof(s_date_time_buffer) - 1, "%B %Y", timeinfo);

    return s_date_time_buffer;
}

bool
DATE_Init()
{
	bool result = false;

	s_systime = new SYSTEMTIME();
	if (s_systime == NULL)
    {
        F_ERROR(("new failed!\n"));
        goto exit;
    }

	result = true;

exit:

	return result;
}

bool
DATE_ConvertLocalTime(const char* a_str)
{
	F_PRINT(("date passed:|%s|\n", a_str));

	return s_parser.convertLocalTime(a_str, s_systime);
}

int
DATE_CompareTime(const char* strTime1, const char* strTime2)
{
	return s_parser.compareTime(strTime1, strTime2, s_systime);
}

bool
DATE_ExtractLocalTime(char* timezn, char* buffer_localtime, unsigned int buffer_length)
{
	return s_parser.extractLocalTime(timezn, buffer_localtime, buffer_length);
}

void
DATE_Free()
{
	delete s_systime;

    s_systime = NULL;
}
